package com.yincb.aop;

import com.yincb.annotation.DS;
import com.yincb.constans.DataSourceConstants;
import com.yincb.helper.DynamicDataSourceHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;

@Component
@Aspect
public class DynamicDataSourceAspect {

    @Pointcut("execution(public * com.yincb.entity.mapper.*.*(..))")
    public void dataSourcePointCut() {
    }

    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        Object target = joinPoint.getTarget();

        DS ds = null;

        if (target instanceof Proxy) {

            Proxy proxy = (Proxy) target;

            Class<?>[] interfaces = proxy.getClass().getInterfaces();

            if (interfaces != null && interfaces.length > 0) {
                ds = interfaces[0].getAnnotation(DS.class);
            }
        }

        String dsKey = DataSourceConstants.DS_KEY_YCB01;

        if (ds != null) {
            dsKey = ds.value();
        }

        DynamicDataSourceHelper.setDynaDBKey(dsKey);

        try {

            return joinPoint.proceed();

        } finally {
            DynamicDataSourceHelper.removeDynaKey();
        }

    }

}
